//
//  ExpresserViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/24.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ExpresserViewController.h"
#import "ExpressReceiveViewController.h"
#import "ReceivedExpressViewController.h"
#import "ReturnExpressViewController.h"
#import "ReturnDetailViewController.h"
#import "ReturnListViewController.h"
#import "SingleScanViewController.h"
#import "ExpresserDBModel.h"
#import "SocketRequest.h"
#import "Singleton.h"

@interface ExpresserViewController ()<SocketRequestDelegate,SingleScanViewControllerDelegate> {
    SocketRequest *_socketRequest;
    ExpresserDBModel *_expresser;
}

@end

@implementation ExpresserViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"接收自提件";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _inputBgView.layer.borderWidth = 0.5;
    _inputBgView.layer.borderColor = LineColor.CGColor;
    if (self.expressSendType == ExpressSendTypeZiti) {
        self.title = @"接收自提件";
        [self rightBarButtonItemTitle:@"已接收" Method:@selector(pullReceive)];
    } else if (self.expressSendType == ExpressSendTypeVisit) {
        self.title = @"接收上门件";
        [self rightBarButtonItemTitle:@"已接收" Method:@selector(pullReceive)];
    } else if (self.expressSendType == ExpressSendTypeReturn) {
        self.title = @"退件";
        [self rightBarButtonItemTitle:@"已退件" Method:@selector(pullReturn)];
        [_nextBtn setTitle:@"开始退件" forState:UIControlStateNormal];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_phoneTextField resignFirstResponder];
}

- (void)pullReceive {
    [MobClick event:@"tuijian_link_yituijian"];
    ReceivedExpressViewController *receivedEVC = [[ReceivedExpressViewController alloc] initWithNibName:@"ReceivedExpressViewController" bundle:nil];
    receivedEVC.expressSendType = self.expressSendType;
    [self.navigationController pushViewController:receivedEVC animated:YES];
}

- (void)pullReturn {
    ReturnListViewController *returnLVC = [[ReturnListViewController alloc] initWithNibName:@"ReturnListViewController" bundle:nil];
    [self.navigationController pushViewController:returnLVC animated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark 验证快递员身份是否合法
- (void)expresserCheckSocketWithTelephone:(NSString *)phone {
    [ToastActivity makeActivity:@"快递员身份验证中..." InView:self.view];;
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS1"]];
    [mutableData appendBytes:[SocketMethod checkLegal:phone] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//获取批次号
- (void)getBatchNoSocket {
    [ToastActivity makeActivity:@"加载中..." InView:self.view];;
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS2"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    if (![string isEqualToString:filtered]) {
        return NO;
    }
    if (_expresser) {
        _expresser = nil;
        textField.text = @"";
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if (_expresser) {
        _expresser = nil;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length != 11) {
        [DSToast showText:@"手机号输入不正确" InView:self.view ShowType:DSToastShowTypeCustom];
        return NO;
    } else {
        [self expresserCheckSocketWithTelephone:_phoneTextField.text];
    }
    [textField resignFirstResponder];
    return YES;
}

#pragma mark SingleScanViewControllerDelegate
- (void)didFinishSingleScanningCode:(NSString *)code {
    if (_expresser) {
        _expresser = nil;
    }
    _phoneTextField.text = code;
    [self expresserCheckSocketWithTelephone:code];
}

#pragma mark ExpresserTextFieldDelegate
- (void)didFinishEditingExpresserTextField {
    [self expresserCheckSocketWithTelephone:_phoneTextField.text];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        if (socket.socketTag == 1) {//获取快递员信息
            [ToastActivity dismissInView:self.view];
            _expresser = [[ExpresserDBModel alloc] initWithData:data Telephone:_phoneTextField.text];
            [_expresser saveExpresserDBModel];
            NSString *sqlString = [NSString stringWithFormat:@"WHERE websiteId = '%@' ORDER BY saveday DESC",[Singleton shareInstance].userMessage.websiteId];
            NSArray *array = [ExpresserDBModel findByCriteria:sqlString];
            if (array.count > 20) {
                ExpresserDBModel *expresser = [array lastObject];
                [expresser deleteObject];
            }
            _phoneTextField.text = [NSString stringWithFormat:@"%@(%@)",_expresser.expressCompanyName,_expresser.expresserName];
        } else {//获取批次号
            NSString *batchNo = [SocketMethod stringData:data];
            ExpressReceiveViewController *expressRVC = [[ExpressReceiveViewController alloc] initWithNibName:@"ExpressReceiveViewController" bundle:nil];
            expressRVC.expresser = _expresser;
            expressRVC.expressSendType = self.expressSendType;
            expressRVC.batchNo = batchNo;
            [self.navigationController pushViewController:expressRVC animated:YES];
        }
    } else {
        [DSToast showText:msg InView:self.view];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity dismissInView:self.view];
    [DSToast showText:msg InView:self.view];
}

#pragma mark NibAction
- (IBAction)startScanExpresserPhone:(id)sender {
    SingleScanViewController *singleSVC = [[SingleScanViewController alloc] initWithNibName:@"SingleScanViewController" bundle:nil];
    singleSVC.delegate = self;
    [self.navigationController pushViewController:singleSVC animated:YES];
}

- (IBAction)startReceiveExpressAction:(id)sender {
    if (_expresser == nil) {
        if ([_phoneTextField isFirstResponder]) {
            [DSToast showText:@"请选择快递员" InView:self.view ShowType:DSToastShowTypeCenter];
        } else {
            [DSToast showText:@"请选择快递员" InView:self.view];
        }
    } else {
        [MobClick event:@"tuijian_btn_kaishituijian"];
        ReturnExpressViewController *returnEVC = [[ReturnExpressViewController alloc] initWithNibName:@"ReturnExpressViewController" bundle:nil];
        returnEVC.expresser = _expresser;
        [self.navigationController pushViewController:returnEVC animated:YES];
    }
}

- (void)dealloc {
    _socketRequest = nil;
    _expresser = nil;
}

@end
